package akbderby.page;

import java.util.List;

import akbderby.model.Question;
import akbderby.model.Quiz;
import akbderby.service.QuizService;

import com.google.appengine.api.datastore.Key;

public abstract class QuizBasePage extends BasePage {

    protected QuizService service = new QuizService();

    protected Quiz getQuiz() {
        return service.getQuiz(getQuizFromSession());
    }

    protected Quiz getQuiz(String id) {
        return service.getQuiz(id);
    }

    protected List<Question> getQuestions() {
        Quiz quiz = getQuiz();
        return quiz.getQuesionListRef().getModelList();
    }

    protected Question getQuestion(int questionNo) {
        Quiz quiz = getQuiz();
        Question question = null;
        List<Question> questions = quiz.getQuesionListRef().getModelList();
        if (!isEmpty(questions)) {
            for (Question q : questions) {
                if (questionNo == q.getQuestionNo()) {
                    question = q;
                    break;
                }
            }
        }
        return question;
    }

    protected Question getQuestion(Quiz quiz, int questionNo) {
        Question question = null;
        List<Question> questions = quiz.getQuesionListRef().getModelList();
        if (!isEmpty(questions)) {
            for (Question q : questions) {
                if (questionNo == q.getQuestionNo()) {
                    question = q;
                    break;
                }
            }
        }
        if (isNull(question)) {
            question = new Question();
            question.getQuizRef().setModel(quiz);
        }
        return question;
    }

    protected void setQuizKeyWithSession(Key quizKey) {
        sessionScope("quizKey", quizKey);
    }

    protected Key getQuizFromSession() {
        return sessionScope("quizKey");
    }

}
